//
//  PhotoBrowserCell.swift
//  JJWeibo
//
//  Created by JJ on 15/9/14.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
protocol PhotoBrowserCellDelegate:NSObjectProtocol{
    
    func photoBrowserCellDidZoom(scale:CGFloat)
    func photoBrowserCellEndZoom()
}
class PhotoBrowserCell: UICollectionViewCell {
    
    weak var PhotoBrowserDelegate:PhotoBrowserCellDelegate?
    var url:NSURL?{
        didSet{
        
            resetScrollView()
            
            indicator.startAnimating()
            imageView.image = nil
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_MSEC)), dispatch_get_main_queue()){
                
            self.imageView.sd_setImageWithURL(self.url, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached]) { (image, error, _, _) -> Void in
                
                self.indicator.stopAnimating()
                if error != nil{
                    SVProgressHUD.showErrorWithStatus("网络不行啊少年")
                    return
                }
                
                self.setImagPosition()
            }
        }
        }
        
    }

    private func resetScrollView(){
        
        scrollView.contentSize=CGSizeZero
        scrollView.contentOffset=CGPointZero
        scrollView.contentInset=UIEdgeInsetsZero
    }
    
    private func setImagPosition(){
        
        let size = displayImage(imageView.image!)
        
        imageView.frame = CGRect(origin: CGPointZero, size: size)
        
        if size.height < scrollView.bounds.height{
            let y=(scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset=UIEdgeInsetsMake(y, 0, 0, 0)
        }else{
            
            scrollView.contentSize=size
        }
        
    }
    
    private func displayImage(image:UIImage)->CGSize{
        
        let scale = image.size.width / image.size.height
        
        let w = scrollView.bounds.width
        let h = w / scale
        return CGSize(width: w, height: h)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI(){
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        var rect=bounds
        rect.size.width -= 20
        
        scrollView.frame=rect
        
        contentView.addSubview(indicator)
        indicator.center=scrollView.center
        
        prepareScrollView()
        
    }
    
    private func prepareScrollView(){
        
        scrollView.delegate=self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        
    }
    
    private lazy var scrollView = UIScrollView()
    
    lazy var imageView :UIImageView={
       
        let image=UIImageView()
        image.contentMode=UIViewContentMode.ScaleAspectFill
        image.clipsToBounds=true
        return image
    }()
    
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
    
}
extension PhotoBrowserCell:UIScrollViewDelegate{
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }

    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
    
        var offsetX=(scrollView.bounds.width - imageView.frame.width) * 0.5
        
        var offsetY = (scrollView.bounds.height - imageView.frame.height) * 0.5
        
        offsetX = (offsetX < 0) ? 0:offsetX
        offsetY = (offsetY < 0) ? 0:offsetY
        
        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
        PhotoBrowserDelegate?.photoBrowserCellEndZoom()

    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        PhotoBrowserDelegate?.photoBrowserCellDidZoom(imageView.transform.a)
        
    }
    
}
